//
//  DBManager.m
//  HDYS
//
//  Created by qianfeng on 15-4-28.
//  Copyright (c) 2015年 kay. All rights reserved.
//

#import "DBManager.h"
#import "FMDatabase.h"

@interface DBManager ()
{
    NSLock *_lock;
    FMDatabase *_dataBase;
}
@end

@implementation DBManager

+(DBManager *)sharedManager{
    static DBManager *_DB = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_DB == nil) {
            _DB = [[DBManager alloc] init];
        }
    });
    return _DB;
}

-(instancetype)init {
    if (self = [super init]) {
        NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/appdb2.db"];
        _dataBase = [FMDatabase databaseWithPath:path];
        if ([_dataBase open]) {
            NSString *sql = @"create table if not exists app(id var(32),gname var(128),pic var(1024))";
            BOOL isSuccess = [_dataBase executeUpdate:sql];
            if (isSuccess) {
                NSLog(@"创建成功");
            } else {
                NSLog(@"创建失败");
            }
        } else {
            NSLog(@"打开数据库失败");
        }
    }
    return self;
}

//插入
-(BOOL)insertDataWithModel:(MainDataModel *)model{
    [_lock lock];
    NSString *sql = @"insert into app(id,gname,pic) values(?,?,?)";
    BOOL isSeccess = [_dataBase executeUpdate:sql, model.gId, model.gname, model.pic];
    if (isSeccess) {
        NSLog(@"插入成功");
    } else {
        NSLog(@"插入失败 %@",_dataBase.lastErrorMessage);
    }
    [_lock unlock];
    return isSeccess;
}

//删除
-(BOOL)deleteDataWithModel:(MainDataModel *)model{
    [_lock lock];
    NSString *sql = @"delete from app where id = ?";
    BOOL isSeccess = [_dataBase executeUpdate:sql, model.gId];
    if (isSeccess) {
        NSLog(@"删除成功");
    } else {
        NSLog(@"删除失败 %@",_dataBase.lastErrorMessage);
    }
    [_lock unlock];
    return isSeccess;
}
//查找全部
-(NSArray *)allData{
    [_lock lock];
    NSString *sql = @"select * from app";
    FMResultSet *set = [_dataBase executeQuery:sql];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    while ([set next]) {
        MainDataModel *model = [[MainDataModel alloc] init];
        model.gId = [set stringForColumn:@"id"];
        model.gname = [set stringForColumn:@"gname"];
        model.pic = [set stringForColumn:@"pic"];
        [array addObject:model];
    }
    [_lock unlock];
    return array;
}
@end
